package com.cloxtec.scada.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MsgParserThread extends Thread {

    private MsgManager msgManager;
    private boolean bExitThread;
    private int nThreadId;
    private MqttMsgHandler msgHandler;

    public MsgParserThread(MqttMsgHandler msgHandler, MsgManager msgManager, int nThreadId) {
        bExitThread = false;
        this.nThreadId = nThreadId;
        this.msgManager = msgManager;
        this.msgHandler = msgHandler;
    }
    @Override
    public void run() {
        while (true) {
            try {
                JSONObject msg = msgManager.getMsg();
                if (msg != null) {
                    //log.info("线程" + nThreadId + "收到消息，开始解析...");
                    long start = System.currentTimeMillis();
                    log.info("[INFO]-[线程:" + nThreadId + " 收到消息，开始解析...]");
                    String topic = msg.getString("_topic");
                    msg.remove("_topic");
                    msgHandler.parseMsg(topic, msg, nThreadId);
                    log.info("[INFO]-[线程:" + nThreadId + " 解析完成，耗时： " + (System.currentTimeMillis() - start) + " ms");
                }
                Thread.sleep(1);
            } catch (InterruptedException e) {
//                e.printStackTrace();
                log.info("线程：" + nThreadId + "有异常信息：" + e.getMessage());
            }

            if (bExitThread) {
                break;
            }
        }
    }
}
